package com.shujia.flink.window

import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer

object Demo2SessionWindow {

  def main(args: Array[String]): Unit = {


    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment


    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")


    val consumer = new FlinkKafkaConsumer[String]("test_topic1", new SimpleStringSchema(), properties)

    consumer.setStartFromLatest()

    val kafkaDS: DataStream[String] = env.addSource(consumer)


    val kvDS: KeyedStream[(String, Int), String] = kafkaDS.map((_, 1)).keyBy(_._1)


    /**
      * 会话窗口，隔一段事件没有数据过来进行计算（会话结束
      * ProcessingTimeSessionWindows 处理时间会话窗口
      * EventTimeSessionWindows 事件时间的会话窗口
      *
      */


    kvDS.window(ProcessingTimeSessionWindows.withGap(Time.seconds(5)))
      .sum(1)
      .print()

    env.execute()


  }

}
